package com.example.javaproject.controller;

import com.example.javaproject.common.R;
import com.example.javaproject.entity.User;
import com.example.javaproject.entity.Student;
import com.example.javaproject.service.UserService;
import com.example.javaproject.service.StudentService;
import com.example.javaproject.util.JwtUtil;
import com.example.javaproject.dto.LoginDTO;
import com.example.javaproject.dto.RegisterDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Date;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

@RestController
@RequestMapping("/api")
public class LoginController {
    @Autowired
    private UserService userService;
    
    @Autowired
    private StudentService studentService;

    @PostMapping("/login")
    public R login(@RequestBody LoginDTO dto) {
        User user = userService.login(dto.getUsername(), dto.getPassword());
        if (user == null) {
            return R.error("用户名或密码错误");
        }
        String token = JwtUtil.createToken(user.getId(), user.getRole());
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("role", user.getRole());
        data.put("username", user.getUsername());
        return R.ok(data);
    }

    @PostMapping("/register")
    public R register(@RequestBody RegisterDTO dto) {
        try {
            // 检查用户名是否已存在
            QueryWrapper<User> query = new QueryWrapper<>();
            query.eq("username", dto.getUsername()).eq("is_deleted", 0);
            User existingUser = userService.getOne(query);
            if (existingUser != null) {
                return R.error("用户名已存在");
            }

            // 检查邮箱是否已存在
            query = new QueryWrapper<>();
            query.eq("mail", dto.getEmail()).eq("is_deleted", 0);
            existingUser = userService.getOne(query);
            if (existingUser != null) {
                return R.error("邮箱已被注册");
            }

            // 检查手机号是否已存在
            query = new QueryWrapper<>();
            query.eq("phone", dto.getPhone()).eq("is_deleted", 0);
            existingUser = userService.getOne(query);
            if (existingUser != null) {
                return R.error("手机号已被注册");
            }

            // 创建新用户
            User newUser = new User();
            newUser.setUsername(dto.getUsername());
            newUser.setPassword(dto.getPassword());
            newUser.setMail(dto.getEmail());
            newUser.setPhone(dto.getPhone());
            newUser.setRole(1); // 默认为学生角色
            newUser.setIsVerified(0);
            newUser.setIsDeleted(0);
            newUser.setCreateTime(LocalDateTime.now());
            newUser.setUpdateTime(LocalDateTime.now());

            boolean userSaved = userService.save(newUser);
            if (!userSaved) {
                return R.error("用户创建失败");
            }

            // 创建学生记录
            Student newStudent = new Student();
            newStudent.setName(null); // 学生姓名为null，后续可完善
            newStudent.setCollege(null); // 院系为null，后续可完善
            newStudent.setContact(null); // 紧急联系人为null，后续可完善
            newStudent.setIsDeleted(0); // 0表示未删除
            newStudent.setCreateTime(LocalDateTime.now());
            newStudent.setUpdateTime(LocalDateTime.now());
            newStudent.setUserId(newUser.getId()); // 关联用户ID

            boolean studentSaved = studentService.save(newStudent);
            if (!studentSaved) {
                // 如果学生记录创建失败，删除已创建的用户记录
                userService.removeById(newUser.getId());
                return R.error("学生信息创建失败");
            }

            return R.ok("注册成功");
        } catch (Exception e) {
            return R.error("注册失败: " + e.getMessage());
        }
    }
} 